#!/usr/bin/perl
use strict;
# use warnings;

#####################################################

# my ($USAGE) =  "\n\n\t****** USAGE of preprocess.pl PROGRAM ******\n\n\n\n\tUSAGE: perl $0 <panam.ini file> \n\n\n\n";
# die "$USAGE" if ((scalar(@ARGV))< 1);
# my $option_file = $ARGV[0];
my $option_file = "panam.ini";
chomp($option_file);

die "\n\n\t=> Cannot find configuration file: $option_file.\n\n" unless (-e $option_file);
die "\n\n\t=> Configuration file, $option_file, appears to be empty!\n\n" if (-z $option_file);
open(OFILE, "<$option_file") || die "Cannot open input file : $option_file\n";

my $usearch;
my $NGS_id_Results;
my $panam_output = "panam_output";
# my $parsing;
my $query_seq; 
my $user_file;
my $preprocess_output = "preprocess_output";
my $seq_F;
my $seq_R;
my $primF;
my $primR;
my $trim =0;
my $path = "bin/uclust3.0.617";
my $us_version = "3.0.617";
####
# my $lib = "lib"; # Tung: no need
# my $fast = "$lib/FastTree"; # Tung: no need
# my $align = "$lib/hmmalign"; # Tung: no need
my $Reference = "Reference" ;
# my $build = "$lib/hmmbuild"; # Tung: no need
####
my $dom;
my %dom;
my $aff_norm;


while (<OFILE>) {
	chomp;
	my $line = $_;

# discard blank line
	if ($line =~ m/^\s*$/g) {
		next;
	}

# discard comment line
	elsif($line =~ m/^\s*#/g) {
		next;
	}
	
# get input options line
        else {
		
		if($line=~m/454_RUN_IDENTIFIER/gi) { 
			$line=~s/454_RUN_IDENTIFIER//gi;
			$line=~s/\t//gi;
			$line=~s/^\s+//gi;
			$line=~s/\s+$//gi;
			if($line) {
				$NGS_id_Results = $line; 
			}
	 		die "\n\tOutput directory for NGS analyses is not defined. Check panam.ini.\n\n" unless ( $NGS_id_Results ne "");
			unless (-d $NGS_id_Results) { mkdir $NGS_id_Results || die "\n\tCould not create Directory $NGS_id_Results $!\n"; }
		}

# 		if (-d $NGS_id_Results."/".$panam_output) { `rm -r $NGS_id_Results/$panam_output` } 
		if (!(-d $NGS_id_Results."/".$panam_output)) { mkdir $NGS_id_Results."/".$panam_output || die "\n\tCould not create Directory $NGS_id_Results/$panam_output $!\n"; }


#		if($line=~m/QUERY_SEQUENCES/gi) {
#			$line=~s/QUERY_SEQUENCES//gi;
#			$line=~s/\t//gi;
#			$line=~s/^\s+//gi;
#			$line=~s/\s+$//gi; 
#			if($line) {
#				$query_seq = $line; 
#			}
#			chomp ($query_seq);
#			# See if the query sequences file exist and contains something
#			die "\n\n\tCannot find query sequence file: $query_seq. Check panam.ini.\n\n" unless (-e $query_seq);
#			die "\n\n\tQuery sequence file, $query_seq, appears to be empty!\n\n" if (-z $query_seq);
#			
#			my $ligne1= `sed -n '1p' $query_seq`;
#			my $ligne2= `sed -n '2p' $query_seq`;	
#			if (($ligne1 !~ /^>/) or ($ligne2 !~ /^[atcguATCGU]/)) {
#				die "\n\n\tYour file $query_seq does not seem to contain sequences in fasta format.\n\n";
#			}		
#		}

		if($line=~m/USER_FILE/gi) {
			$line=~s/USER_FILE//gi;
			$line=~s/\t//gi;
			$line=~s/^\s+//gi;
			$line=~s/\s+$//gi;
			if($line) {
				$user_file = $line; 
			}
			die "\n\n\t User file value missed. Check panam.ini.\n\n" unless (($user_file ne ""));
			die "\n\n\t Invalid user file value!\n\n" unless (($user_file eq "own") or ($user_file eq "pooledSamples") or ($user_file eq "eachSample"));	
		}

#		if($line=~m/REFERENCE_BASE/gi) {
#			$line=~s/REFERENCE_BASE//gi;
#			$line=~s/\t//gi;
#			$line=~s/^\s+//gi;
#			$line=~s/\s+$//gi;
#			if($line) {
#				$Reference = $line; 
#			}
#		}

		if($line=~m/FORWARD_PRIMER_NAME/gi) {
			$line=~s/FORWARD_PRIMER_NAME//gi;
			$line=~s/\t//gi;
			$line=~s/^\s+//gi;
			$line=~s/\s+$//gi;
			if($line) {
				$primF = $line; 
			}
		}
	
		if($line=~m/REVERSE_PRIMER_NAME/gi) {
			$line=~s/REVERSE_PRIMER_NAME//gi;
			$line=~s/\t//gi;
			$line=~s/^\s+//gi;
			$line=~s/\s+$//gi;
			if($line) {
				$primR = $line; 
			}
		}

		if($line=~m/FORWARD_PRIMER_SEQUENCE/gi) {
			$line=~s/FORWARD_PRIMER_SEQUENCE//gi;
			$line=~s/\t//gi;
			$line=~s/^\s+//gi;
			$line=~s/\s+$//gi;
			if($line) {
				$seq_F = $line; 
			}
		}
	
		if($line=~m/REVERSE_PRIMER_SEQUENCE/gi) {
			$line=~s/REVERSE_PRIMER_SEQUENCE//gi;
			$line=~s/\t//gi;
			$line=~s/^\s+//gi;
			$line=~s/\s+$//gi;
			if($line) {
				$seq_R = $line;
			}
		}

		############### normalisation
		if($line=~m/NBR_SEQ_NORM/gi) {
			$line=~s/NBR_SEQ_NORM//gi;
			$line=~s/\t//gi;
			$line=~s/^\s+//gi;
			$line=~s/\s+$//gi;
			if($line) {
				$aff_norm = $line; #print "aff --- $aff_norm\n";
			} 
		}
		
		#####################################

		if($line=~m/DOMAIN/gi) {
			$line=~s/DOMAIN//gi;
			$line=~s/\t//gi;
			$line=~s/^\s+//gi;
			$line=~s/\s+$//gi;
			if($line) { 
				$dom = $line;			
				if (defined $dom ) { #push (@dom, $dom);
					$dom{$dom} = 1
				}
			}
			foreach my $d (keys %dom) {
				die "\n\n\t Domain name is not correct. Check panam.ini.\n\n" unless (($d eq "bacteria") or ($d eq "eukaryota") or ($d eq "archaea"));
			}	
		}
	}
}

die "\n\n\t Invalid number of sequences to pick for the normalization! Check panam.ini.\n\n" if ((defined $aff_norm ) and ($aff_norm !~ /^\d+$/));
if (!(defined $aff_norm)) {$aff_norm = '200' }


print "$Reference\n";

############################################# trimmed profiles path ######################################################
# # # 
if (!(defined $primF) and (defined $primR))  {
	die "\n\n\t Primer forward not defined. Check panam.ini.\n\n";
}

if (defined $primF) {
	die "\n\n\t Primer reverse not defined. Check panam.ini.\n\n" unless (defined $primR);
	die "\n\n\t Primers' sequences missed. Check panam.ini.\n\n" unless ((defined $seq_F) and (defined $seq_R));
	die "\n\n\t Primers' sequences seem to be in the wrong format. Check panam.ini.\n\n" unless (($seq_F =~ /[ATCGUatcgu]/) and ($seq_R =~ /[ATCGUatcgu]/));
	$trim = 1
}

my @tax=();
my $Profiles;

if ($trim == 1) {
	#$Profiles = "Reference/Profiles_".$primF."_".$primR;
	$Profiles = "Reference/Trimmed_Profiles";
	if ((-d $Profiles)) {
		print "Trimmed profiles exist in $Profiles/\n";

	}
}

 
if ($trim == 0) {
	$Profiles= "Reference/Profiles";
}


print "################################### CUTTING\n";
my @tax = ();
open (IL, "<Reference/sortingtax");
@tax = <IL>;
chomp(@tax);
close IL;

#my $rep = $NGS_id_Results."/".$panam_output."/Similarity_annotation/Sorted_Sequences/files_";
#my @listefic = <$rep*>;			
#foreach my $nn (@listefic) { 
#	foreach my $dn (@dom){
#		if ($nn =~ /$dn/) { 
#			if ($nn=~ /Similarity_annotation\/Sorted_Sequences\/files_([^\/]+)/) { 
#				my $taxo = $1 ; 
#				push (@tax, $taxo);
#			}
#		}
#	}
#}



#my $max=0;
open (TT, ">".$NGS_id_Results."/taxonomic_groups");
foreach my $e (@tax) { 
	print "Debug\n";
	my $aa; my %hh; my $i= 0; my $num=1; 
	if (-e $NGS_id_Results."/".$panam_output."/Similarity_annotation/Sorted_Sequences/files_".$e."/seq_".$e) {

		open (AA,  $NGS_id_Results."/".$panam_output."/Similarity_annotation/Sorted_Sequences/files_".$e."/seq_".$e);
		while (<AA>) {
			if ($_=~/^(>.*?)\s/) {
				$aa = $1;
			}
			else {
				$hh{$aa}.=$_;
			}	
		}
		open (P, ">".$NGS_id_Results."/".$panam_output."/Similarity_annotation/Sorted_Sequences/files_".$e."/file_cut");
		print TT "$e\n";
		foreach my $ee (keys %hh) {
			$i++;
			if ($i != 10001) {
 				print P "$ee\n$hh{$ee}\n";
			}
			else  {
				close P;
				$num++;
				unless (-e "$NGS_id_Results/$panam_output/Similarity_annotation/Sorted_Sequences/files_".$e.$num) { `mkdir $NGS_id_Results/$panam_output/Similarity_annotation/Sorted_Sequences/files_$e$num`; }
				open (P, ">".$NGS_id_Results."/".$panam_output."/Similarity_annotation/Sorted_Sequences/files_".$e.$num."/file_cut");
				print TT "$e$num\n";		
				print P "$ee\n$hh{$ee}\n";
				$i= 1;
				
			}
		}
		close P;
		#if ($num > $max) { $max = $num}
	}		
}
close TT;
print "End cutting\n";
#my @num = (1 .. $max);
# 
# # ##############################""
# 
#`mkdir $NGS_id_Results/$panam_output"/Phylogeny"` ;
#`mkdir $NGS_id_Results/$panam_output"/Alignment"`;
#`mkdir $NGS_id_Results/$panam_output"/Phylogeny/Node_files"`;



